package org.example.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.domain.Menu;
import org.example.query.MenuQuery;
import org.example.service.IMenuService;
import org.example.utils.AjaxResult;
import org.example.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    public IMenuService menuService;

    /**
     * 保存和修改公用的
     * @param menu 传递的实体
     * @return Ajaxresult转换结果
     * @auth caiwen
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult save(@RequestBody Menu menu) {
        try {
            if (menu.getId() != null){
                    menuService.updateById(menu);
            }else{
                    menuService.save(menu);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！" + e.getMessage());
        }
    }

    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
                menuService.removeById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除对象失败！" + e.getMessage());
        }
    }

    //获取用户
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Menu get(@PathVariable("id") Long id) {
        return menuService.getById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<Menu> list() {
        return menuService.list();
    }
    //使用原生的mybaits完成一个  查询所有的方法
    @GetMapping("/findAll")
    public List<Menu> findAll(){
        return menuService.findAll();
    }

    /**
    * 分页查询数据(不带查询条件))
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @RequestMapping(value = "/pagelist", method = RequestMethod.POST)
    public PageList<Menu> json(@RequestBody MenuQuery query) {
        Page<Menu> page = new Page<Menu>(query.getPage(), query.getRows());
        page = menuService.page(page);
        return new PageList<Menu>(page.getTotal(),page.getRecords());
    }
}
